<template>
  <div>
    <el-drawer :model-value="visible" title="项目信息" size="680px" @close="closeHandle" @closed="closed">
      <div class="full box">
        <el-scrollbar>
          <el-form :model="form" ref="formRef" label-width="100" :rules="formRules" label-position="left">
            <el-form-item label="业务公司" required prop="yewu_company" :label-width="formLabelWidth">
              <el-select v-model="form.yewu_company" filterable default-first-option :reserve-keyword="false"
                         placeholder="请选择业务公司">
                <el-option v-for="item in company" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>

            <el-form-item label="项目名称" prop="name" required :label-width="formLabelWidth">
              <el-input v-model="form.name" placeholder="请输入项目名称" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="工期" required prop="gongqi" :label-width="formLabelWidth">
              <el-input v-model="form.gongqi" placeholder="请输入工期" type="number" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="业务员" required prop="yewu" :label-width="formLabelWidth">
              <el-select v-model="form.yewu" filterable default-first-option :reserve-keyword="false"
                         placeholder="请选择业务员">
                <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="项目总金额" prop="xiangmu_price">
              <el-input type="number" v-model="form.xiangmu_price" placeholder="请输入项目总金额"/>
            </el-form-item>
            <el-form-item label="是否设计" required prop="is_ui" :label-width="formLabelWidth">
              <el-radio-group v-model="form.is_ui">
                <el-radio label="1">需要</el-radio>
                <el-radio label="0">不需要</el-radio>
              </el-radio-group>
            </el-form-item>
            <!--  -->


            <!-- <el-form-item label="产品" required prop="chanpin" :label-width="formLabelWidth">
              <el-select
                  v-model="form.chanpin"
                  filterable
                  default-first-option
                  :reserve-keyword="false"
                  placeholder="请选择产品"
              >
                <el-option
                    v-for="item in userList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="项目状态" prop="status" required :label-width="formLabelWidth">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option v-for="(item) in statusEnum" :key="item.value"
                           :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item> -->
            <el-form-item label="签单日期" prop="qiandan_date" required :label-width="formLabelWidth">
              <el-date-picker v-model="form.qiandan_date" type="date" placeholder="请选择日期" :size="size"/>
            </el-form-item>
            <el-form-item label="合同到期" prop="daoqi_date" :label-width="formLabelWidth">
              <el-date-picker v-model="form.daoqi_date" type="date" placeholder="请选择日期" :size="size"/>
            </el-form-item>
            <el-form-item label="技术要求" :label-width="formLabelWidth">
              <el-input placeholder="请输入技术要求" v-model="form.yaoqiu" show-word-limit rows="4" type="textarea"
                        autocomplete="off"/>
            </el-form-item>
            <el-form-item label="项目备注" :label-width="formLabelWidth">
              <el-input v-model="form.beizhu" placeholder="请输入备注" show-word-limit rows="4" type="textarea"
                        autocomplete="off"/>
            </el-form-item>
            <el-form-item label="合同文件">
              <el-upload
                  v-model:file-list="fileList"
                  class="upload-demo"
                  action="/api/common/upload"
                  multiple
                  :limit="3"
                  :auto-upload="false"
                  :on-change="uploadChange"
                  ref="fileRef"
              >
                <el-button type="primary">上传文件</el-button>
                <template #tip v-if="!fileList.length">
                  <div class="el-upload__tip">
                    上传合同文件.
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item label="合同图片">
              <el-upload
                  v-model:file-list="imageList"
                  action="/api/common/upload"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
              >
                <el-icon>
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image"/>
      </el-dialog>
      <template #footer>
        <el-space>
          <el-button type="info" plain :loading="loading" @click="cancelHandle">取消</el-button>
          <el-button type="primary" :loading="loading" @click="confirmHandle">提交保存</el-button>
        </el-space>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import {uploadFile} from '@/api/common'
import {ref, reactive, computed, watch} from "vue";
import {getUsers} from "@/api/user";
import {addProjectBus, editProject} from "@/api/project.js";
import {listsnopage} from "@/api/service.js";
import {STATUS_ENUM} from "@/views/project-list/status";
import {toast} from "@/hook/toast";
import {delay} from "@/utils";
import {ElMessage, ElMessageBox} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import {preview} from 'vue3-image-preview'

const dialogVisible = ref(false)
const dialogImageUrl = ref('')

function handlePictureCardPreview(ev) {
  preview({images: [ev.response.data['fullurl']]})
}

const fileRef = ref(null)
const fileList = ref([])
const imageList = ref([])
const form = reactive({
  yewu_company_name: "",
  yewu_company: "",
  name: "",
  status: '',
  gongqi: "",
  qiandan_date: "",
  daoqi_date: "",
  yewu: '',
  chanpin: '',
  yaoqiu: '',
  beizhu: '',
  isEdit: false,
  id: '',
  is_ui: '1',
  xiangmu_price: ''
});

function uploadChange(ev) {
  const {raw, uid} = ev
  const formData = new FormData()
  formData.set('file', raw)
  uploadFile(formData).then(resp => {
    toast({title: '上传成功'})
    const target = fileList.value.find(item => item.uid = uid)
    if (!target) return
    target.status = 'success'
    target.response = resp
  }).catch(err => {
    fileRef.value.handleRemove(uid)
  })

}

function uploadSuccess(ev) {
  console.log(ev, 'uploadSuccess')
  console.log(fileList.value)

}

const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
      `The limit is 3, you selected ${files.length} files this time, add up to ${
          files.length + uploadFiles.length
      } totally`
  )
}

const beforeRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
      `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
      () => true,
      () => false
  )
}

const formRules = computed(() => ({
  yewu_company: [
    {
      required: true,
      message: '请输入业务公司',
      trigger: 'change',
    }
  ],
  name: [
    {
      required: true,
      message: '请输入项目名称',
      trigger: 'change',
    }
  ],
  gongqi: [
    {
      required: true,
      message: '请输入工期',
      trigger: 'change',
    }
  ],
  yewu: [
    {
      required: true,
      message: '请选择业务员',
      trigger: 'blur'
    }
  ],
  is_ui: [
    {
      required: true,
      message: '请选择是否设计',
      trigger: 'blur'
    }
  ],
  status: [
    {
      required: true,
      message: '请选择项目状态',
      trigger: 'blur'
    }
  ],
  chanpin: [
    {
      required: true,
      message: '请选择业务员',
      trigger: 'blur'
    }
  ],
  qiandan_date: [
    {
      required: true,
      message: '请选择签单日期',
      trigger: 'blur'
    }
  ],
  daoqi_date: [
    {
      required: true,
      message: '请选择到期日期',
      trigger: 'blur'
    }
  ],
  xiangmu_price: [
    {
      required: true,
      message: '请输入项目总金额',
    }
  ]
}))
const formRef = ref(null)
const loading = ref(false);
const size = ref("default");

// 是否默认选择
const radio1 = ref('1')

const formLabelWidth = "90px";
const statusEnum = computed(() => STATUS_ENUM)
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  }
})
const emits = defineEmits(['update:modelValue', 'addSuccess'])

const cancelHandle = () => {
  visible.value = false
}

function closed() {
  resetForm()
}

const visible = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emits('update:modelValue', value)
  }
})
const userList = ref([])

async function initUserList() {
  const resp = await getUsers()
  const {code, data, msg} = resp
  if (code !== 1) return
  if (!!data && data.length) {
    userList.value = data.map(item => {
      const {id, nickname} = item
      return {value: id, label: nickname}
    })
  }
}

// 获取公司列表
const company = ref([])

async function companyList() {
  const resp = await listsnopage()
  const {code, data, msg} = resp
  if (code !== 1) return
  console.log(resp, 'resp')
  if (!!data && data.length) {
    company.value = data.map(item => {
      const {id, name} = item
      return {value: id, label: name}
    })
  }
}

function resetForm() {
  form.yewu_company_name = ''
  form.yewu_company = ''
  form.name = ''
  form.chanpin = ''
  form.yewu = ''
  form.status = ''
  form.beizhu = ''
  form.yaoqiu = ''
  form.qiandan_date = ''
  form.daoqi_date = ''
  form.gongqi = ''
  form.xiangmu_price = ''
  formRef.value.resetFields()
  fileList.value = []
  imageList.value = []
}

watch(() => props.modelValue, value => {
  if (!value) {
    return
  }
  initUserList()

  companyList()
})

const closeHandle = () => {
  visible.value = false
};

function editHandle(row) {
  const {
    yewu_company_name,
    yewu_company,
    chanpin_user,
    status,
    yewu_user,
    qiandan_date,
    daoqi_date,
    name,
    gongqi,
    content,
    jishu_yaoqiu_content,
    id
  } = row
  form.yewu_company_name = yewu_company_name
  form.yewu_company = yewu_company
  form.name = name
  form.chanpin = chanpin_user
  form.yewu = yewu_user
  form.status = status
  form.beizhu = content
  form.yaoqiu = jishu_yaoqiu_content
  form.qiandan_date = qiandan_date
  form.daoqi_date = daoqi_date
  form.gongqi = gongqi
  visible.value = true
  form.isEdit = true
  form.id = id
}

defineExpose({
  editHandle,
})


function reqMethod(data) {
  if (form.isEdit) return editProject(data)
  return addProjectBus(data)
}

function getFileAndImage() {
  const files = fileList.value.filter(item => item.status === 'success').map(item => item.response.data.fullurl)
  const images = imageList.value.filter(item => item.status === 'success').map(item => item.response.data.fullurl)
  return {
    files: files.join(','),
    images: images.join(',')
  }
}

function confirmHandle() {
  formRef.value.validate(async flag => {
    if (!flag) return
    loading.value = true
    const {files, images} = getFileAndImage()
    const {
      yewu_company,
      name,
      gongqi,
      qiandan_date,
      daoqi_date,
      yewu,
      chanpin,
      beizhu,
      yaoqiu,
      is_ui,
      xiangmu_id,
      xiangmu_price,
    } = form
    const payload = {
      yewu_company_id: yewu_company,
      name,
      yewu_user: yewu,
      content: beizhu,
      jishu_yaoqiu_content: yaoqiu,
      daoqi_date,
      qiandan_date,
      gongqi,
      is_ui,
      xiangmu_id,
      files,
      images,
      xiangmu_price
    }
    if (form.isEdit) payload.xiangmu_id = form.id
    console.log(payload, 'payload')
    const resp = await addProjectBus(payload)
    form.isEdit = false
    const {code, msg} = resp
    await delay(200)
    toast({title: msg})
    loading.value = false
    if (code !== 1) return
    triggerUpdate()
  })
}

function triggerUpdate() {
  emits('addSuccess')
  resetForm()
  visible.value = false
}
</script>


<style scoped lang="scss"></style>
